package com.javalab.recorder.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class ApplicationContext {
	private static Properties properties;

	private static Logger logger = Logger.getLogger(ApplicationContext.class);

	private static final String DefaultCapturingMixerName = "capture.mixer.name";
	static {
		logger.info("Loading configuration info.");
		properties = new Properties();
		File file = new File("recorder.properties");
		if (file.exists()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream("recorder.properties");
				properties.load(fis);
			} catch (FileNotFoundException e) {
				logger.error(e.getMessage(), e);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			} finally {
				try {
					fis.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		logger.debug("Loading configuration info complete.");
	}

	public static String getDefaultCapturingMixerName() {
		return properties.getProperty(DefaultCapturingMixerName, null);
	}

	public static void setDefaultCapturingMixerName(String mixerName) {
		properties.setProperty(DefaultCapturingMixerName, mixerName);
		save();
	}

	private static void save() {
		logger.info("Save configuration info.");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File("recorder.properties"));
			properties.store(fos, "");
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		logger.debug("Save configuration info complete.");
	}
}
